<?php
declare (strict_types=1);

namespace app\course\logic\base\admin;

use app\common\exception\LogicException;
use app\course\model\base\admin\CourseCertConfig as CourseCertConfigModel;

/**
 * Class CourseCertConfig
 *
 * @package app\course\logic\base\admin
 */
class CourseCertConfig extends CourseCertConfigModel
{

    /**
     * 获取证书配置
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/9/29
     *
     * @param int $courseId
     * @return CourseCertConfig|array|\think\Model
     */
    public function getCertConfigByCourseId(int $courseId)
    {
        return $this->where('course_id', $courseId)->findOrEmpty();
    }

    /**
     * 保存配置
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/9/29
     *
     * @param int   $courseId
     * @param array $data
     */
    public function saveCertConfig(int $courseId, array $data)
    {
        $config = $this->getCertConfigByCourseId($courseId);
        if ($config->isEmpty()) {
            $config->course_id = $courseId;
        }
        $config->has_cert           = $data['has_cert'] ?? 0;
        $config->condition          = $data['condition'] ?? [];
        $config->course_is_finished = $data['course_is_finished'] ?? 0;

        if (!$config->save()) {
            throw new LogicException('保存失败');
        }
    }
}